from fastapi import APIRouter, BackgroundTasks
from typing import List, Dict, Any
from datetime import datetime

router = APIRouter()

@router.get("/list")
async def get_alerts(
    status: str = "all",
    limit: int = 20
) -> Dict[str, Any]:
    """获取异常告警列表"""
    return {
        "alerts": [
            {
                "id": "ALT001",
                "type": "ph_anomaly",
                "message": "地块P001 pH值异常：当前值5.2，正常范围6.0-7.5",
                "severity": "high",
                "timestamp": datetime.now().isoformat(),
                "plot_id": "P001",
                "status": "active"
            },
            {
                "id": "ALT002",
                "type": "moisture_low",
                "message": "地块P003 土壤湿度偏低：当前值12%，建议灌溉",
                "severity": "medium",
                "timestamp": datetime.now().isoformat(),
                "plot_id": "P003",
                "status": "active"
            },
            {
                "id": "ALT003",
                "type": "soc_decrease",
                "message": "地块P005 SOC含量持续下降，建议增施有机肥",
                "severity": "low",
                "timestamp": datetime.now().isoformat(),
                "plot_id": "P005",
                "status": "resolved"
            }
        ],
        "total": 3
    }

@router.post("/send")
async def send_alert(
    background_tasks: BackgroundTasks,
    alert_data: Dict[str, Any]
):
    """发送告警通知"""
    # 模拟发送邮件
    background_tasks.add_task(send_email_alert, alert_data)
    return {"message": "告警通知已发送", "alert_id": "ALT004"}

@router.put("/{alert_id}/resolve")
async def resolve_alert(alert_id: str):
    """标记告警为已解决"""
    return {"message": f"告警 {alert_id} 已标记为已解决"}

def send_email_alert(alert_data: Dict[str, Any]):
    """发送邮件告警（模拟）"""
    print(f"发送邮件告警：{alert_data.get('message', '未知告警')}")
